#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include "ts.h"
#include "hires.h"
#include "sockets.h"
#include "netopt.h"

char http[4096];
char body[4096];

int main(int ac,char** av){
	struct netopt* op = netopt(ac,av);
	int sock, result, len, answer_len, rid;
	double start,end;
	char* answer_ptr;
	rid = time(0);
	if(op == 0){
		return 1;
	}
	if(0 == *op->addr){
		printf("need addr\n");
		return 1;
	}
	if(0 == op->port){
		printf("need port\n");
		return 1;
	}
	if(op->count == 0){
		op->count = 1;
	}
	if(op->timing){
		start = hires();
	}
	
	for(int i = 0; i < op->count; i++){

		sprintf(body,
"<body rid='%d' xmlns='http://jabber.org/protocol/httpbind' sid='13183e0666dfc9137cc30027fe5e3c421a35d681'>"
"<message to='1_120@rooms.localhost' from='smenshikh@localhost/Carnage' type='groupchat' xmlns='jabber:client'>"
"<body>22222222222222%d</body></message></body>\n",rid,rid);
		rid++;
		sprintf(http,
			"POST /chb/ HTTP/1.0\n"
			"Host: test.karnage.ru\n"
			"User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:2.0) Gecko/20100101 Firefox/4.0\n"
			"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\n"
			"Accept-Language: ru-ru,ru;q=0.8,en-us;q=0.5,en;q=0.3\n"
			"Accept-Encoding: gzip, deflate\n"
			"Accept-Charset: windows-1251,utf-8;q=0.7,*;q=0.7\n"
			"Content-Length: %d\n"
			"Connection: close\n"
			"Content-Type: text/plain; charset=UTF-8\n"
			"\n"
			"%s",
			strlen(body),body);
		len = strlen(http);

		if(op->verbose){
			printf("Try: \n%s\n",http);
		}
		sock = make_connect(op->addr, op->port, op->laddr, op->lport);
		if(!sock){
			return 1;
		}
		result = send_message(sock,http,len);
		if(!result){
			return 1;
		}
		result = recv_message(sock,&answer_ptr,&answer_len,&read_all);
		if(!result){
			free(answer_ptr);
			return 1;
		}
		answer_ptr[answer_len] = 0;
		if(op->verbose){
			printf(answer_ptr);
			printf("\n");
		}
		free(answer_ptr);
		close_connect(sock);
	}
	if(op->timing){
		end = hires();
		printf("Res: count=%d time=%f speed=%f\n",op->count,end-start,op->count/(end-start));
	}
	return 0;
}
